package com.psg.controller;

import com.psg.exception.RuleDoesNotMeetException;
import com.psg.pojo.Car;
import com.psg.pojo.Produce;
import com.psg.pojo.User;
import com.psg.service.CarService;
import com.psg.service.ProduceService;
import com.psg.util.Result;
import com.psg.vo.CarProduceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Controller
@RequestMapping("/user/car")
public class CarController extends BaseController {

    @Autowired
    private CarService carService;
    @Autowired
    private ProduceService produceService;

    @RequestMapping("/list")
    private ModelAndView toCar(ModelAndView mav) {
        Integer userId = getUserId();
        List<CarProduceVo> carProduceList = carService.findMyCarProduces(userId);
        for (CarProduceVo carProduceVo : carProduceList) {
            carProduceVo.buildPropertyText();
        }
        mav.setViewName("car");
        mav.addObject("carList", carProduceList);
        mav.addObject("carCount", carProduceList.size());
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        carProduceList.forEach(carProduceVo -> {
            totalPrice.updateAndGet(v -> v + carProduceVo.getPrice() * carProduceVo.getAccount());
        });
        mav.addObject("totalPrice", totalPrice.get());
        return mav;
    }

    @GetMapping("/countCar")
    @ResponseBody
    public Result countCar() {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.success().add("count", 0);
        }
        Long count = carService.getCarIdAccount(userId);
        return Result.success().add("count", count);
    }


    @RequestMapping("/showCar")
    public String ShowCar(@RequestParam("id") Integer id, Model model) {
        List<Car> cars = carService.findMyCar(id);
        model.addAttribute("carList", cars);
        return "car";
    }

    @RequestMapping("/updateCar/{pId}/{count}")
    @ResponseBody
    public Long updateCar(@PathVariable("pId") Integer pId,
                          @PathVariable("count") Integer count,
                          HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        Integer uId = user.getuId();
        return carService.updateCar(uId, pId, count);
    }

    @RequestMapping("/deleteCar/{id}")
    public void deleteCar(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        carService.deleteCar(id);
        User user = (User) request.getSession().getAttribute("loginUser");
        request.getRequestDispatcher("/showCar?id=" + user.getuId()).forward(request, response);
    }

    @PostMapping("/addProduce")
    @ResponseBody
    public Result addProduce(int id, int count) {
        try {
            if (count == 0) return Result.error("参数异常！");
            Produce produce = produceService.selectProduce(id);
            if (null == produce) return Result.error("要添加的商品不存在!");
            Integer userId = getUserId();
            if (null == userId) return Result.error("用户信息异常！");
            carService.updateCar(userId, produce.getpId(), count);
            return Result.success();
        } catch (Exception e) {
            return Result.error("添加购物车失败！");
        }
    }

    @PostMapping("/deleteCarProduce")
    @ResponseBody
    public Result deleteCarProduce(int id) {
        if (getUserId() == null) {
            return Result.error("用户信息错误！");
        }
        try {
            carService.deleteCarProduce(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除购物车商品失败！");
        }
    }

    @PostMapping("/addCarProduceAccount")
    @ResponseBody
    public Result addCarProduceAccount(int id) {
        if (getUserId() == null) {
            return Result.error("用户信息错误！");
        }
        try {
            carService.updateCarProduceAccount(id, 1);
            return Result.success();
        } catch (RuleDoesNotMeetException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改购物车商品数量失败！");
        }
    }

    @PostMapping("/subCarProduceAccount")
    @ResponseBody
    public Result subCarProduceAccount(int id) {
        if (getUserId() == null) {
            return Result.error("用户信息错误！");
        }
        try {
            carService.updateCarProduceAccount(id, -1);
            return Result.success();
        } catch (RuleDoesNotMeetException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改购物车商品数量失败！");
        }
    }

    @PostMapping("/computeTotalPrice")
    @ResponseBody
    public Result computeTotalPrice(@RequestParam("ids[]") int[] ids){
        if (ids.length == 0) return Result.success().add("totalPrice",0d);
        try {
            Double totalPrice = carService.computeTotalPriceByIds(ids);
            return Result.success().add("totalPrice",totalPrice);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算价格失败！");
        }
    }
}
